var version = -1;
var isSendOrder = false;

var trade = function(){
	if(debug){
		debug = false;
		$("#startOrStop").html("状态：启用");
		window.setTimeout(function(){start();}, 1000);
	} else{
		$("#startOrStop").html("状态：停用"); 
		debug = true;
	}
};


var PriceDigits = {
	digits : {
		"EURUSD" : 	5
		,"GBPUSD" : 5
		,"USDJPY" : 3
		,"USDCAD" : 5
	}
	,fix : function(symbol,price){
		var rst = "";
		if(!symbol || !price)return rst;
		var _di = this.digits[symbol];
		var _price = price.split(".");
		rst = _price[0]+"."+_price[1].substring(0,_di);
		return rst;
	}
};
var orderSend = function(obj,type){
	var symbol = $(obj).parent().parent().attr("id");
	var url = PATH + "/trade/index!orderSend.do";
	var params = "pm.type="+type+"&pm.symbol="+symbol;
	$.getJSON(url,params,function(data){
		if(data.indexOf("error")!=-1){
			alert(data.split(":")[1]);
		}
	});	
};

var getHistory = function(){
	var url = PATH + "/trade/index!getOrderHistory.do";
	var params = "";
	$.getJSON(url,params,function(data){
		if(!data)return;
		$("#orderHistoryTbl").find("tr:gt(0)").remove();
		var list = data.split(";");
		//$("#historyTotal").html("共"+(list.length-1)+"条");
		for(var i=list.length-1;i>=0;i--){
			var order = list[i].split(",");
			var magic = order[0];
			if(!magic)continue;
			var type = (order[1]=="0")?"买":"卖";
			var volume = order[2];// 手数
			var symbol = order[3];
			var price = PriceDigits.fix(symbol,order[4]);
			var nowPrice = PriceDigits.fix(symbol,order[5]);
			var profit = order[6];
			var openTime = order[7];
			var closeTime = order[8];
			var tr = "<tr><td>"+(i+1)+".</td><td>"+magic+"</td>"+"<td>"+type+"</td><td>"+volume+"</td>"
						+"<td>"+symbol+"</td><td>"+price+"</td><td>"+nowPrice+"</td><td>"+profit+"</td>"
						+"<td>"+openTime+"</td><td>"+closeTime+"</td>"
					+"</tr>";
			$("#orderHistoryTbl").append(tr);
		}
	});
};

var closeOrder = function(obj){
	$(".opt > a").each(function(){
			this.className="btn_style03";
		});
		$(".closeOpt > a").each(function(){
			this.className="btn_style03";
		});
	var oTr = $(obj).parent().parent();
	var symbol = oTr.find(".symbol").val();
	var magic = oTr.find(".magicNo").val();
	var url = PATH + "/trade/index!orderSend.do";
	var params = "pm.symbol="+symbol+"&pm.type=9&pm.magic="+magic;
	$.getJSON(url,params,function(data){
		if(data.indexOf("error")!=-1){
			alert(data.split(":")[1]);
		}
	});
};



$(function(){
	
	var initSymbolList = function(){
		var optBtns = "<a href='javascript:;' class='btn_style07' onclick='orderSend(this,\"0\")' ><span>买</span></a>&nbsp;"
			+"<a href='javascript:;' class='btn_style07' onclick='orderSend(this,\"1\")' ><span>卖</span></a>";
		$(".symbolTbl .opt").html(optBtns);
	};
	
	var setSymbolInfo = function(data){
		var list = data.split(";"); 
		for(var i=0;i<list.length;i++){
			var symbol = list[i].split(",");
			var oTr = $("#"+symbol[0]);
			oTr.find(".name").html(symbol[0]);
			oTr.find(".sellPrice").html(PriceDigits.fix(symbol[0],symbol[1]));
			oTr.find(".buyPrice").html(PriceDigits.fix(symbol[0],symbol[2])); 
		} 
	};

	var setSendOrderStatusNormal = function(){
		var html = "可交易";
		$("#sendOrdersDiv").html(html);
		$(".sendOrderStatus").css("color","#3A6E1A");
		$(".opt > a").each(function(){
			this.className="btn_style07";
		});
		$(".closeOpt > a").each(function(){
			this.className="btn_style06";
		});
		return true;
	};
	
	var setSendOrders = function(data){
		if(!data)return setSendOrderStatusNormal();
		var magic = "";
		for(var index in data){
			magic = index;
			break;
		}
		if(!magic)return setSendOrderStatusNormal();
		if($("#timer").length>0)return;
		var order = data[magic] || {};
		isSendOrder = true;
		$(".opt > a").each(function(){
			this.className="btn_style03";
		});
		$(".closeOpt > a").each(function(){
			this.className="btn_style03";
		});
		var symbol = order.symbol;
		var type = order.type;
		if(type=="9")type = "平仓";
		else if(type=="0")type = "买";
		else type = "卖";
		var html = "正在提交订单["+magic+"]：&nbsp;"+type+"&nbsp;&nbsp;"+symbol+"&nbsp;&nbsp;请稍候...<span id='timer'>50</span>";
		$("#sendOrdersDiv").html(html);
		$(".sendOrderStatus").css("color","#2273CB");
		countdown("#timer",function(){
			var url = PATH + "/trade/index!clearSendOrders.do";
			$.getJSON(url,"",function(data){});
			setSendOrderStatusNormal();
		});
	};
	var setTimeout = function(fn,delay){
		if(typeof fn == "function"){
			var arrayArgs = Array.prototype.slice.call(arguments,2);
			var _fn = (function(){
				fn.apply(null,arrayArgs);
			});
			window.setTimeout(_fn,parseInt(delay));
		}
	};
	
	var countdown = function(elem,callback){
		elem = $(elem);
		var time = elem.html() || 30;
		time = parseInt(time) - 1;
		if(time == 0){
			elem.html(time);
			callback();
		}else {
			elem.html(time);
			setTimeout(countdown, 1000,elem,callback);
		}
	};
	
	var setOrderList = function(data){
		var list = data.split(";");
		var orderTbl = $(".orderList");
		//orderTbl.find("tr:gt(0)").remove();
		var newMagicArr = [];
		var oldMagicArr = [];
		for(var i=0;i<list.length;i++){
			var order = list[i].split(",");
			var magic = order[0];
			if(!magic)continue;
			newMagicArr.push(magic);
			var type = order[1];
			type = (type=="0")?"买":"卖";
			var volume = order[2];// 手数
			var symbol = order[3];
			var price = PriceDigits.fix(symbol,order[4]);
			var bidPrice = PriceDigits.fix(symbol,order[5]);
			var askPrice = PriceDigits.fix(symbol,order[6]);
			var nowPrice = (type == "买")?bidPrice:askPrice;
			var profit = parseInt(nowPrice.replace(".","")) - parseInt(price.replace(".",""));
			if(type == "卖")
				profit = profit * -1;
			var exist = false;
			orderTbl.find(".magicNo").each(function(){
				oldMagicArr.push(this.value);
				if(this.value==magic){
					exist = true;
					var _oTr = $(this).parent().parent();
					_oTr.find(".nowPrice").html(nowPrice);
					_oTr.find(".profit").html(profit);
				}
			});
			if(!exist){
				var td = "<tr><td>"+magic+"</td>"+"<td>"+type+"</td><td>"+volume+"</td>"
				+"<td>"+symbol+"</td><td>"+price+"</td><td class='nowPrice'>"+nowPrice+"</td><td class='profit'>"+profit+"</td>";
				td += "<td class='closeOpt'><a href='javascript:;' class='btn_style06' onclick='closeOrder(this)' ><span>平仓</span></a><input type='hidden' class='symbol' value='"+symbol+"' /><input type='hidden' class='magicNo' value='"+magic+"' /></td></tr>";
				orderTbl.append(td);
				oldMagicArr.push(magic);
			}
		}
		if(oldMagicArr.length == 0 || newMagicArr.length == 0){
			orderTbl.find("tr:gt(0)").remove();
		}
		if(newMagicArr.length!=oldMagicArr.length){
			for(var i=0;i<oldMagicArr.length;i++){
				var _oM = oldMagicArr[i];
				var _flag = false;
				for(var j=0;j<newMagicArr.length;j++){
					if(_oM == newMagicArr[j]){
						_flag = true;
					}
				}
				if(!_flag){
					orderTbl.find(".magicNo").each(function(){
						if(this.value == _oM){
							$(this).parent().parent().remove();
						}
					});
					break;
				}
			}	
		}
	};
	
	window.start = function(){
		var url = PATH + "/trade/index!start.do";
		$.getJSON(url,"",function(data){
			var v = data.v;
			if(v<=version) return false;
			
			version = v;
			
			setSymbolInfo(data.symbolInfo);
			setSendOrders(data.sendOrders);
			setOrderList(data.orderList);
			if(data.isCloseOrder){
				initAccountInfo();
			}
		});	
		if(!debug)
			window.setTimeout(function(){start();}, 1000);
	};
	
	// 获取帐户信息
	window.initAccountInfo = function(){
		var url = PATH + "/trade/index!getAccountInfo.do";
		$.getJSON(url,"",function(data){
			 var info = data.split(",");
			 $("#username").html(username); 
			 $("#money").html(info[1]);
		});	
	};
	
	var initPage = function(){
		// 获取帐户信息
		initAccountInfo(); 
		initSymbolList();
		start();

		
	};
	
	initPage();

});